package com.selfdiscipline.ui.screens.task

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.selfdiscipline.data.local.entity.TaskEntity
import com.selfdiscipline.domain.repository.TaskRepository
import com.selfdiscipline.domain.usecase.task.GetPendingTasksUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.time.LocalDateTime

/**
 * ViewModel for the Task Screen
 */
@HiltViewModel
class TaskViewModel @Inject constructor(
    private val getPendingTasksUseCase: GetPendingTasksUseCase,
    private val taskRepository: TaskRepository
) : ViewModel() {
    
    // UI state
    private val _uiState = MutableStateFlow(TaskUiState())
    val uiState: StateFlow<TaskUiState> = _uiState.asStateFlow()
    
    init {
        loadTasks()
    }
    
    /**
     * Load all pending tasks
     */
    private fun loadTasks() {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true) }
            
            taskRepository.getActiveTasks().collect { tasks ->
                _uiState.update { 
                    it.copy(
                        tasks = tasks,
                        isLoading = false
                    )
                }
            }
        }
    }
    
    /**
     * Mark a task as complete
     */
    fun completeTask(task: TaskEntity) {
        viewModelScope.launch {
            val updatedTask = task.copy(
                isCompleted = !task.isCompleted,
                completedAt = if (!task.isCompleted) LocalDateTime.now() else null
            )
            taskRepository.updateTask(updatedTask)
        }
    }
    
    /**
     * Handle task click
     */
    fun onTaskClick(taskId: String) {
        _uiState.update { 
            it.copy(selectedTaskId = taskId) 
        }
    }
    
    /**
     * Handle add task click
     */
    fun onAddTaskClick() {
        _uiState.update { 
            it.copy(showAddTask = true) 
        }
    }
    
    fun deleteTask(taskId: Long) {
        viewModelScope.launch {
            taskRepository.deleteTask(taskId)
        }
    }
}

/**
 * UI state for the Task Screen
 */
data class TaskUiState(
    val tasks: List<TaskEntity> = emptyList(),
    val selectedTaskId: String? = null,
    val isLoading: Boolean = true,
    val showAddTask: Boolean = false,
    val error: String? = null
) 